using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class QuestManager : Singleton<QuestManager>
{
    public class QuestTask
    {
        public QuestData_SO questData;

        public QuestState TaskState
        {
            get
            {
                if (questData != null)
                    return questData.questState;
                return QuestState.Start;
            }
            set
            {
                if (questData != null)
                    questData.questState = value;
            }
        }
    }
    /// <summary>
    /// 玩家的任务列表
    /// </summary>
    public List<QuestTask> tasks = new List<QuestTask>();

    private void Start()
    {
        LoadQuestSystem();
    }
    /// <summary>
    /// 判断任务列表中是否已存在某个任务
    /// </summary>
    /// <param name="questData"></param>
    /// <returns></returns>
    public bool HaveTask(QuestData_SO questData)
    {
        if (questData != null)
        {
            return tasks.Any(q => q.questData.questName == questData.questName);
        }
        else
        {
            return false;
        }
    }
    public QuestTask GetQuestTask(QuestData_SO questData)
    {
        return tasks.Find(q => q.questData.questName == questData.questName);
    }
    /// <summary>
    /// 敌人死亡、拾取物品时更新任务需求的进度
    /// </summary>
    /// <param name="requireName"></param>
    /// <param name="amount"></param>
    public void UpdateQuestProcess(string requireName, int amount)
    {
        // 找到每一个 任务中 任务需求的名字 和 刚刚击败的敌人名字相同 的 任务
        foreach (var task in tasks)
        {
            // 跳过已交付的任务
            if (task.TaskState == QuestState.Finish)
            {
                continue;
            }
            
            var matchTask = task.questData.questRequires.Find(r => r.name == requireName);

            if (matchTask != null)
            {
                matchTask.currentAmount += amount;
            }

            task.questData.CheckQuestProgress();
        }
    }
    public void LoadQuestSystem()
    {
        int tasksCount = PlayerPrefs.GetInt("TaskCount");
        for (int i = 0; i < tasksCount; i++)
        {
            // 重新创建任务数据的 scriptableObject 并赋值
            QuestData_SO questData = ScriptableObject.CreateInstance<QuestData_SO>();
            SaveManager.Instance.Load(questData, "task" + i);
            tasks.Add(new QuestTask() { questData = questData });
        }
    }
    // 保存所有任务信息
    public void SaveQuestSystem()
    {
        PlayerPrefs.SetInt("TaskCount", tasks.Count);
        for (int i = 0; i < tasks.Count; i++)
        {
            SaveManager.Instance.Save(tasks[i].questData, "task" + i);
        }
    }
}
